﻿app.controller('SearchController', ['$scope', '$http', 'toaster', function ($scope, $http, toaster) {
    $scope.currentCarList = [];
    $scope.totalPages = [];
    $scope.searchText = '';

    $scope.pageSize = 3;
    $scope.totalCarCount = 0;
    $scope.currentPageNum = 1;

    $scope.search = function () {
        executeSearch($scope.currentPageNum);
    };

    $scope.getNextResults = function (pageNum) {
        $scope.currentPageNum = pageNum;
        executeSearch($scope.currentPageNum);
    };

    var executeSearch = function (pageNum) {
        $http({
            method: 'GET',
            url: '/api/Search/' + $scope.searchText + '?pageNum=' + pageNum
        }).success(function (data) {
            $scope.currentCarList = data.currentCarList;
            $scope.totalCarCount = data.totalCarCount;

            $scope.totalPages.length = 0;
            for (var i = 0; i < (data.totalCarCount / $scope.pageSize) ; i++) {
                $scope.totalPages.push({ pageNum: i + 1 });
            }
        }).error(function (data, status) {
            toaster.pop('error', "Something went wrong", status);
        });
    }

    executeSearch(1);
}]);